<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>06_防抖-获取的返回值</title>
</head>

<body>

  <button>按钮</button>

  <input type="text">
  <button class="cancel">取消</button>

  <script>

    function debounce(fn, delay, immediate = false) {
      let timer = null;
      let isImmediate = true;
      const _debounce = function (...args) {
        return new Promise((resolve, reject) => {
          try {
            if (timer) {
              clearTimeout(timer)
            }
            if (isImmediate && immediate) {
              resolve(fn.apply(this, args))
              isImmediate = false
            } else {
              timer = setTimeout(() => {
                // fn.apply(this, arguments) // this指向调用debounce函数的元素，arguments是事件对象
                resolve(fn.apply(this, args))
                timer = null // 清空timer，防止内存泄漏
                isImmediate = false
              }, delay)
            }
          } catch (error) {
            reject(error)
          }
        })
      }

      _debounce.cancel = function () {
        if (timer) {
          clearTimeout(timer)
          timer = null
          isImmediate = false
        }
      }

      return _debounce
    }

    // 3.防抖处理代码
    let counter = 1
    const inputEl = document.querySelector('input')
    const cancelBtn = document.querySelector(".cancel")
    const debounceFn = debounce(function (name, age, height) {
      console.log(`发送网络请求${counter++}:`, name, age, height)
      return 111
    }, 3000, true)

    // inputEl.oninput = debounceFn

    // // 4.实现取消的功能
    // cancelBtn.onclick = function() {
    //   debounceFn.cancel()
    // }

    debounceFn("张三", 18, 1.88).then(res => {
      console.log("res: ", res)
    })
  </script>

</body>

</html>